package com.fwtai.service.api;

import com.fwtai.api.ApiCollectDao;
import com.fwtai.bean.PageFormData;
import com.fwtai.config.LocalUserId;
import com.fwtai.tool.IdBuilder;
import com.fwtai.tool.ToolClient;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;

/**
 * 收藏知识
 * @作者 田应平
 * @版本 v1.0
 * @QQ号码 444141300
 * @创建日期 2021年7月22日 11:43:17
 * @官网 <url>http://www.fwtai.com</url>
*/
@Service
public class ApiCollectService{

    @Resource
    private ApiCollectDao apiCollectDao;

    public String addCollect(final String knowledgeId){
        if(knowledgeId == null || knowledgeId.length() <=0){
            return ToolClient.jsonValidateField();
        }
        final String query = apiCollectDao.queryExist(knowledgeId);
        if(query == null){
            return ToolClient.createJsonFail("收藏的内容不存在");
        }
        final String loginId = LocalUserId.get();
        final HashMap<String,String> params = new HashMap<>(3);
        params.put("loginId",loginId);
        params.put("knowledgeId",knowledgeId);
        final String exist = apiCollectDao.queryCollect(params);
        if(exist == null){
          params.put("kid",String.valueOf(new IdBuilder().getId121L()));
            return ToolClient.executeRows(apiCollectDao.addCollect(params),"收藏成功","收藏失败");
        }else{
            return ToolClient.executeRows(apiCollectDao.delCollect(params),"取消成功","取消失败");
        }
    }

    public String getCollect(final HttpServletRequest request){
        final String loginId = LocalUserId.get();
        final PageFormData formData = ToolClient.pageParamsApi(request);
        if(formData == null) return ToolClient.jsonValidateField();
        formData.put("loginId",loginId);
        return ToolClient.jsonPage(apiCollectDao.getCollect(formData));
    }

    public String delById(final String kid){
        if(kid == null || kid.length() <= 0){
            return ToolClient.jsonValidateField();
        }
        final HashMap<String,String> params = new HashMap<>(2);
        final String loginId = LocalUserId.get();
        params.put("kid",kid);
        params.put("loginId",loginId);
        return ToolClient.executeRows(apiCollectDao.delById(params));
    }
}